package com.ccp.dev.workflow.service;

import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.consts.SystemConst;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.system.dao.SysUserDao;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.workflow.dao.BpmPerformanceDao;
import com.ccp.dev.workflow.dao.TaskReadDao;
import com.ccp.dev.workflow.model.ActDefModel;
import com.ccp.dev.workflow.model.BpmPerformance;
import com.ccp.dev.workflow.model.TaskOpinion;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.model.bpm.TaskRead;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * ClassDescribe 流程处理绩效 Service类
 * @author: fanruiqi
 * Date: 2019-09-02
 * Since:1
 * To change this template use File | Settings | File Templates.
 */
@Service
public class BpmPerformanceService extends BaseService<BpmPerformance> {
    @Resource
    private BpmPerformanceDao bpmPerformanceDao;


    @Resource
    private SysUserDao userDao;
    @Resource
    private BpmService bpmService;
    @Resource
    private TaskReadDao taskReadDao;
    @Resource
    private ActDefModelService actDefModelService;
    @Resource
    private SysOrgService sysOrgService;

    /**
     * 添加数据到BPM_PERFORMANCE表
     * 保存流程处理记录，用于绩效统计
     * @param taskId  ACT_RU_TASK表里的流程任务ID
     * @param processCmd 流程执行实体
     */
    public void addProcessRecord(String taskId, ProcessCmd processCmd) {
        TaskEntity taskEntity = bpmService.getTask(taskId);
        //act流程定义ID
        String procDefId = taskEntity.getProcessDefinitionId();
        //节点任务ID
        String nodeId = taskEntity.getTaskDefinitionKey();
        //bpm流程定义
        ActDefModel actDefModel = actDefModelService.getByProcDefId(procDefId);
        //流程实例ID
        String instanceId = taskEntity.getProcessInstanceId();
        SysUser opeUser = (SysUser) ContextUtil.getCurrentUser();
        String userId;
        String userName="";
        String orgId = "";
        String orgName="";
        if (opeUser == null) {
            //自动处理任务
            userId = SystemConst.SYSTEMUSERID;
            userName = SystemConst.SYSTEMUSERNAME;
        } else {
            if(TaskOpinion.STATUS_COMMON_TRANSTO.toString().equals(taskEntity.getDescription())){
                //正常流转任务
                opeUser = userDao.getById(Long.parseLong(taskEntity.getAssignee()));
            }
            userId = opeUser.getUserId();
            userName = opeUser.getFullName();
        }
        if(opeUser!=null){
            SysOrg opeOrg = sysOrgService.queryOrgsByUserId(userId).get(0);
            orgId = opeOrg.getOrgId();
            orgName = opeOrg.getOrgName();
        }
        //任务读取记录
        TaskRead taskRead = taskReadDao.getTaskReadByUserId(instanceId,taskId,userId);
        BpmPerformance bpf = new BpmPerformance();
        bpf.setId(UUIDUtils.getUUIDFor32());
        //ACT流程定义ID
        bpf.setProcDefId(procDefId);
        //bpm流程定义ID
        bpf.setModefId(actDefModel.getId());
        //流程标题
        bpf.setSubject(actDefModel.getName());
        //ACT流程实例ID
        bpf.setProcInstId(instanceId);
        //流程实例标题
        bpf.setInstSubject(processCmd.getSubject());
        //流程任务节点ID
        bpf.setNodeId(nodeId);
        //流程任务节点名称
        bpf.setNodeName(taskEntity.getName());
        //任务创建时间
        Date createTime = taskEntity.getCreateTime();
        //初次读取任务时间
        Date readTime = taskRead==null?null:taskRead.getCreateTime();
        //任务完成时间
        Date endTime = new Date();
        bpf.setCreateTime(createTime);
        bpf.setReadTime(readTime);
        bpf.setEndTime(endTime);
        if(null!=readTime){
            //创建到读取的持续时间（单位：秒）
            long crDuration = readTime.getTime()-createTime.getTime();
            bpf.setCrDuration(crDuration);
            //读取到完成的持续时间（单位：秒）
            long reDuration = endTime.getTime()-readTime.getTime();
            bpf.setReDuration(reDuration);
        }
        //创建到完成的持续时间（单位：秒）
        long ceDuraton = endTime.getTime()-createTime.getTime();
        bpf.setCeDuration(ceDuraton);
        //任务执行人ID
        bpf.setOpeUserId(userId);
        //任务执行人姓名
        bpf.setOpeUserName(userName);
        //任务执行组织ID
        bpf.setOpeOrgId(orgId);
        //任务执行组织名称
        bpf.setOpeOrgName(orgName);
        int opeType = (int)processCmd.getVoteAgree();
        bpf.setOpeType(opeType);
        bpf.setOpeName(getOpeName(opeType));
        bpmPerformanceDao.add(bpf);
    }
    private String getOpeName(int opeType){
        switch (opeType){
            case 0 :
                return "弃权";
            case 1 :
                return  "同意";
            case 2 :
                return  "反对";
            case 3 :
                return  "驳回";
            case 4 :
                return  "追回";
            case 5 :
                return  "会签通过";
            case 6 :
                return  "会签不通过";
            case 7 :
                return  "知会意见";
            case 21 :
                return  "转办";
            default:
                return  "";
        }
    }
}
